﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
#if NetFx40
using System.Diagnostics.Contracts;
#endif

namespace XYZShell.Helper
{
    public static class StreamHelper
    {
		/// <summary>
		/// 从流中读取所有字节
		/// </summary>
		/// <param name="stream"></param>
		/// <returns></returns>
        public static IEnumerable<byte> ReadAllBytes(this Stream stream)
		{
#if NetFx40
			Contract.Requires(stream.CanRead, "传入流不支持读取操作");
#endif
			int b = -1;
            while ((b=stream.ReadByte())!=-1)
            {
                yield return (byte)b;
            }
        }

		/// <summary>
		/// 把给定字节数据写入到流中
		/// </summary>
		/// <param name="stream"></param>
		/// <param name="bs"></param>
        public static void WriteAllBytes(this Stream stream, IEnumerable<byte> bs)
        {
#if NetFx40
            Contract.Requires(stream.CanWrite, "传入流不支持写入操作");
#endif
            foreach (var by in bs)
            {
                stream.WriteByte(by);
            }
        }
    }
}
